<!-- 登录页面 -->
<template>
  <div class="root">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      class="demo-ruleForm"
    >
      <el-form-item prop="username">
        <el-input v-model="ruleForm.username" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item prop="checkPass">
        <el-input v-model="ruleForm.pwd" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="LoginFn()">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { FormInstance } from "element-plus";
import type { Ref } from "vue";
import { reactive, ref } from "vue";
import { umsAdmin } from "../../request/http";
import { useAdminStore } from "../../store/modules/admin";
import { useRouter, useRoute } from "vue-router";

const adminStore = useAdminStore();

const router = useRouter();

const ruleFormRef = ref() as Ref<FormInstance>;

const ruleForm = reactive({
  username: "admin",
  pwd: "123456",
});
// 校验规则
const rules = reactive({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { validator: valiUsername, trigger: "blur" },
  ],
});

// 校验账号的函数
function valiUsername(
  rule: unknown,
  value: string | undefined,
  cb: (msg?: string) => void
) {
  if (value && value.length > 3) {
    cb();
  } else {
    cb("用户名不能少于3个字符");
  }
}

// 点击登录按钮触发
async function LoginFn() {
  try {
    await ruleFormRef.value.validate();
    //
    const loginData = await umsAdmin.adminLogin({
      username: ruleForm.username,
      password: ruleForm.pwd,
    });

    if (loginData.code === 200) {
      const { tokenHead, token } = loginData.data;
      // 存储localStorage
      localStorage.setItem("token", tokenHead + token);
      // 获取用户信息
      // const adminInfo = await http.getAdminInfo();
      // if (adminInfo.code === 200) {
      //   adminStore.updateMenus(adminInfo.data.menus);
      // 跳转到首页
      router.push("/");
      // }
    }
  } catch (e) {
    console.log("catch");
  }
  //Form validate方法
  // callback
  //   ruleFormRef.value.validate((isVal: boolean) => {
  //     console.log(isVal);
  //   });
  // promise
  //   ruleFormRef.value
  //     .validate()
  //     .then(() => {
  //       console.log("then");
  //     })
  //     .catch(() => {
  //       console.log("catch");
  //     });
}
</script>
<style lang="less" scoped>
.root {
  height: 100%;
  background-color: #2d3a4b;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .el-form-item {
    width: 420px;

    ::v-deep .el-input__inner {
      background-color: transparent;
      border-color: hsla(0, 0%, 100%, 0.1);
      height: 38px;
      line-height: 38px;
      // padding-left: 40px;
    }

    ::v-deep .el-input__prefix {
      font-size: 18px;
    }
  }
  .el-button {
    width: 420px;
  }
}
</style>
